#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/24 9:21
    Desc  :
--------------------------------------
"""
from application import app
import time
from servers.models.ApiCaseSuiteModel import ApiCaseSuite
from servers.servers.ApiCaseServices import ApiCaseRun, ApiCaseServices
from servers.servers.BaseServices import BaseServices


class ApiCaseSuiteServices(BaseServices):

    def __init__(self, document = ApiCaseSuite):
        super().__init__(document)

    def run(self, id):
        fields = {
            'caseAll': 0,
            'casePass': 0,
            'caseFail': 0,
            'caseError': 0,
            'caseSkip': 0,
            'beginTime': round(time.time() * 1000, 0),
            'startTime': round(time.time() * 1000, 0),
            'endTime': 0,
            'costTime': 0,
            'caseResponse': []
        }

        apicaseServices = ApiCaseServices()
        queryset = self.document.objects(id = id).first()

        caseIds = queryset.caseList

        for i in caseIds:
            apicase = ApiCaseRun(apicaseServices.find_by_id(i))
            runCount = apicase.queryset.runCount
            isRun = apicase.queryset.isRun
            caseResult = apicase.queryset.dict_json()
            caseResult['caseAll'] += runCount
            fields['caseAll'] += runCount
            if not isRun:
                caseResult['caseSkip'] += 1
                fields['caseSkip'] += 1
            for j in range(runCount):
                try:
                    apicase.request()
                    if apicase.isApiAssert:
                        caseResult['response'].append(apicase.result)
                        caseResult['casePass'] += 1
                        fields['casePass'] += 1
                    elif not apicase.isApiAssert and apicase.isApiExtract:
                        caseResult['response'].append(apicase.result)
                        caseResult['casePass'] -= 1
                        fields['casePass'] -= 1
                        caseResult['caseFail'] += 1
                        fields['caseFail'] += 1
                except Exception as e:
                    app.logger.error(e)
                    caseResult['response'].append(apicase.result)
                    caseResult['caseError'] += 1
                    caseResult['textError'] = str(e)
                    fields['caseError'] += 1

            fields['caseResponse'].append(caseResult)

        fields['endTime'] = round(time.time() * 1000, 0)
        fields['costTime'] = fields['endTime'] - fields['startTime']
        return fields